/**
 * 项目相关的js代码
 */

/**
 * 显示toast
 * @param message: 显示的提示信息
 */
function show_toast(message = '') {
    if (!message || message.length === 0) {
        return;
    }

    let $toast = $('#toast');
    if ($toast.css('display') !== 'none') {
        return;
    }

    let $toast_content = $('#toast-content');
    $toast_content.text(message);

    $toast.fadeIn(100);
    setTimeout(function () {
        $toast.fadeOut(100);
    }, 2000);
}

/**
 * 显示确认框
 * @param title
 * @param message
 * @param cb
 */
function show_confirm_dialog(title, message, cb) {
    let $confirmDialog = $('#confirmDialog');
    $confirmDialog.fadeIn(200);

    // 点击取消按钮
    let $dialogs = $('#dialogs');
    $dialogs.off('click', '.weui-dialog__btn_default');
    $dialogs.on('click', '.weui-dialog__btn_default', function() {
        $(this).parents('.js_dialog').fadeOut(200);
    });

    // 点击确认按钮
    $dialogs.off('click', '.weui-dialog__btn_primary');
    $dialogs.on('click', '.weui-dialog__btn_primary', function() {
        $(this).parents('.js_dialog').fadeOut(200);
        cb();
    });

    // 设置标题和提示信息
    let $title = $('#confirm-dialog-title');
    $title.text(title);
    let $message = $('#confirm-dialog-message');
    $message.text(message);
}

/**
 *
 * @param url: 请求地址
 * @param data: 请求数据
 * @param confirm_msg: 确认提示
 * @param failed_msg: 失败提示
 * @param success_cb: 成功回调函数
 * @param fail_cb: 失败回调函数
 * @constructor
 */
function my_ajax(url, data={}, confirm_msg='', failed_msg='', success_cb=null, fail_cb=null) {
    if (confirm_msg > 0) {
        if (!confirm(confirm_msg)) {
            return;
        }
    }

    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(result) {
            if (!result.hasOwnProperty('errcode')) {
                return;
            }

            let errcode = result.errcode;
            if (errcode !== 0) {
                if (fail_cb != null) {
                    if (result.message) {
                        show_toast(result.message);
                    }
                    fail_cb(result.message);
                    return;
                }
            } else {
                if (success_cb != null) {
                    success_cb(result.data, result.message);
                    return;
                }
            }

            if (result.message) {
                show_toast(result.message);
            }
        },
        error: function(request, status, error) {
            if (failed_msg) {
                show_toast(failed_msg);
            } else {
                show_toast(error);
            }

            if (fail_cb != null) {
                fail_cb(error);
            }
        }
    });
}

// TODO: REMOVE it!!
function MyGet(url, redirect_url='', success=null, failure=null) {
    axios.get(url)
        .then((response) => {
            if (response.status !== 200) {
                if (failure) {
                    failure();
                    show_toast(`调用失败，错误码${response.status}`)
                }
                return;
            }

            let data = response.data;
            if (!data.hasOwnProperty('errcode')) {
                return;
            }

            if (data.errcode !== 0) {
                if (failure) {
                    failure(data.errcode);
                    show_toast(data.message)
                }
                return;
            }

            if (success) {
                success(data.data);
            }

            if (redirect_url.length > 0) {
                window.location.assign(redirect_url);
            } else {
                window.location.reload();
            }
        })
        .catch((error) => {
            show_toast(error);
            if (failure) {
                failure(error);
                show_toast(error);
            }
        });
}

/**
 * 请求手机号码
 */
function fetch_sms_code(url) {
    const mobile = $('#mobile').val();
    if (!/^\d+$/.test(mobile)) {
        alert("无效的手机号码！");
        return;
    }

    // 隐藏获取验证码按钮
    $('#fetch_sms_button').hide();
    setTimeout(() => {
        $('#fetch_sms_button').show();
    }, 60 * 1000);

    let data = {
        'mobile': mobile,
    };
    new my_ajax(url, data, '', '', () => {
        show_toast('验证码已发送');
        console.log('send');
    });
}

/**
 * 绑定手机号码
 * @param url: 请求的地址
 * @param redirection_url: 重定向地址
 */
function bind_mobile(url, redirection_url) {
    const agree_terms = $("#agree_terms").is(':checked');
    if (!agree_terms) {
        alert("在绑定手机前，请阅读并同意《相关条款》。");
        return;
    }

    const mobile = $('#mobile').val();
    if (!/^\d+$/.test(mobile)) {
        alert("无效的手机号码！");
        return;
    }

    const sms_code = $('#sms_code').val();
    if (!/^\d+$/.test(sms_code)) {
        alert("无效的手机验证码!");
        return;
    }

    let data = {
        'mobile': mobile,
        'sms_code': sms_code,
    };
    new my_ajax(url, data, '', '', () => {
       window.location = redirection_url;
    });
}

/**
 * 跳转到下载页面
 */
function show_download_app_page(url) {
    window.location = url;
}

/**
 * 判断是否是ios设备登录
 * @returns {boolean}
 */
function is_ios_device() {
    let user_agent = navigator.userAgent.toLowerCase();
    if (user_agent.includes('iphone') || user_agent.includes('ipad')) {
        return true;
    }
    return false;
}

/**
 * 判断是否是微信
 *
 * @returns {boolean}
 */
function is_wechat() {
    let ua = window.navigator.userAgent;
    return ua.match(/micromessenger/i) ? true : false;
}

/**
 * 调用手机本地功能
 * @param method
 * @param params
 */
function call_native_function(method, params={}) {
    let message = {
        'method': method,
        'params': params,
    };
    if (is_ios_device()) {
        window.webkit.messageHandlers.hbNativeCall.postMessage(message);
    } else {
        hb.nativeCall(JSON.stringify(message));
    }
}

/**
 * 点击分享按钮
 */
function click_share_button() {
    call_native_function('activity_agent_share', {});
}

/**
 * 创建公会
 *
 * @param url: 请求的地址
 * @param redirection_url: 重定向地址
 */
function create_guild(url, redirection_url) {
    const guild_name = $('#guild_name').val();
    if (!guild_name) {
        alert("无效的公会名称");
        return;
    }

    const chief_uid = $('#chief_uid').val();
    if (!/^\d+$/.test(chief_uid)) {
        alert("无效的会长UID!");
        return;
    }

    let data = {
        'guild_name': guild_name,
        'chief_uid': chief_uid,
    };
    new my_ajax(url, data, '', '', () => {
       window.location = redirection_url;
    });
}

/**
 * 复制文本到黏贴板中
 * @param text
 */
function copy_to_clipboard(text) {
    navigator.clipboard.writeText(text, tips).then(function() {
        if (tips) {
            show_toast(tips);
        }
    }, function(err) {
        console.error('Could not copy text: ', err);
    });
}

/**
 * 代理领取红包
 */
function get_agent_red_pack(url, withdraw_cent, redirection_url) {
    const alipay_account = $('#alipay_account').val();
    if (!alipay_account) {
        alert("无效的支付宝账号");
        return;
    }

    const alipay_payee_real_name = $('#alipay_payee_real_name').val();
    if (!alipay_payee_real_name) {
        alert("真实姓名不可以为空!");
        return;
    }

    let data = {
        'alipay_account': alipay_account,
        'alipay_payee_real_name': alipay_payee_real_name,
        'withdraw_cent': withdraw_cent,
    };
    new my_ajax(url, data, '', '', (data, message) => {
        show_toast(message);
        setTimeout(function () {
            window.location = redirection_url;
        }, 1500);
    }, (message) => {
        show_toast(message);
    });
}

function open_without_referrer(link){
    var meta = document.createElement('meta');
    meta.name = "referrer";
    meta.content = "no-referrer";
    document.getElementsByTagName('head')[0].appendChild(meta);

    window.location = link;
}

/**
 * 延迟跳转到指定的页面
 *
 * @param link
 * @param delay_ms
 */
function redirect(link=null, delay_ms=1000) {
    setTimeout(() => {
        if (link == null) {
            window.history.back();
        } else {
            window.location = link;
        }
    }, delay_ms);
}

/**
 * 使用微信为指定的账号充值
 *
 * @param uid
 * @param rmb
 */
function pay_with_wechat(url, uid, rmb) {
    // 请求预支付信息
    let data = {
        'uid': uid,
        'rmb': rmb,
    };

    new my_ajax(url, data, '', '', (data, msg) => {
        wx.chooseWXPay({
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: function (res) {
                console.log('Pay success!');
            }
        });
    }, (msg) => {
        show_toast(msg);
    });
}

/**
 * 使用支付宝的H5支付方式支付
 * @param uid
 * @param rmb
 */
function pay_with_alih5(uid, rmb) {
    let url = window.location = `/mweb/ap/${uid}/${rmb}/`;
    window.location = url;
}

/**
 * 创建浏览器中打开的tips提示
 *
 * @returns {HTMLDivElement}
 */
function create_open_with_browser_tips() {
    var div = document.createElement('div');
    var p = document.createElement('p');
    var img = document.createElement('img');
    var div1 = document.createElement('div');
    div.appendChild(div1);
    div.appendChild(p);
    div1.appendChild(img);

    var message = '由于微信的限制，无法直接为您安装应用<br />您可以点击右上角的"..."并选择在"浏览器"中打开';

    div.style.cssText = "position: fixed; left: 0px; top: 0px; height: 100%; width: 100%; z-index: 1000; background-color: rgba(0, 0, 0, 0.7);";
    div1.style.cssText = "margin:5px;";
    p.style.cssText = "text-align: left; margin: 20px;padding:20px;margin-top:0; color:black;background-color: rgba(255,255,255, 0.9);font-size:14px;line-height:24px;border-radius:10px;";
    p.innerHTML = message;
    img.style.cssText = "width:97px; height:54px; margin-right: 0; margin-left: auto; display: block; clear: both;";
    img.src = 'https://res.yyzb.com/arrow.png';
    return div;
}

function call_test_function() {
    alert("4");
}

